﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Resources;

namespace ServicioWebRest
{
    public partial class AgentePedidos : System.Web.UI.Page
    {
         #region Constructor
        ResourceManager rm = new ResourceManager(typeof(RecursosWeb));
        public AgentePedidos()
        {
            userRequestUri = rm.GetString("servicioRest") + "/Api/PedidosNuevos";
        }

        #endregion

        #region Fields

        private readonly string userRequestUri = string.Empty;

        #endregion

        #region Methods

        /// <summary>
        /// Page load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Page_Load(object sender, EventArgs e)
        {
            string allUsersJson = GetAllUsers();
            if (string.IsNullOrEmpty(allUsersJson))
            {
                Response.Write(string.Empty);
                return;
            }

            Response.Write(allUsersJson);
        }

        /// <summary>
        /// Get all users
        /// </summary>
        /// <returns>Return client callBack name and json string</returns>
        private string GetAllUsers()
        {
            try
            {
                String usu = Request.QueryString["usu"];
                String estado = Request.QueryString["estado"];
                String desde = Request.QueryString["desde"];
                String hasta = Request.QueryString["hasta"];
                string allUsersUri = string.Format("{0}/" + usu + "," + estado + "," + desde + "," + hasta+"", userRequestUri);
                string callBack = Request.QueryString["callBack"];

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(allUsersUri);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream webStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(webStream);
                string allUsersJson = reader.ReadToEnd();

                reader.Close();
                response.Close();

                return string.Format("{0}({1});", callBack, allUsersJson);
            }
            catch (Exception ex) { return "error"+ex; }
        }

        #endregion Methods
    }
}